package univ.lille1.fr.rest;

import java.io.IOException;
import java.net.SocketException;
import java.util.Calendar;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.net.ftp.FTPFile;

import univ.lille1.fr.rest.bean.UserBean;

@Path("/list")
public class ListService {

	private PasserelleREST rest;
	private UserBean bean;

	@GET
	@Path("/dir{pathname:.*}")
	@Consumes(MediaType.APPLICATION_XML)
	@Produces("text/html")
	public String list(@PathParam ("pathname") String currentPath) {
		this.rest = new PasserelleREST("jeromechv", "u6zbckZt");
//		this.rest = new PasserelleREST("anonymous", "");
		this.bean = this.rest.getBean();
		String message = "";
		String list = "";
		String test = "<html><head><meta charset='utf-8'></head><body><div style='border-bottom: 1px solid #c0c0c0;'><h1>Hello " + this.bean.getUser() + "!</h1><h1>Index de " + currentPath + "</h1></div><br>";

		try {
			this.rest.connect("ftp.jeromecha.fr");
//			this.rest.connect("ftp.univ-lille1.fr");
			this.rest.passivMode();
			if (this.bean.isConnected()) {
				message = "Vous êtes maintenant connecté";

				this.bean.setCurrentPath(currentPath);
				this.rest.cwd(this.bean.getCurrentPath());
				
				String temp = currentPath;
				
				if(!temp.equals("/")){
					if(temp.charAt(temp.length()-1) == '/'){
						temp = temp.substring(0, temp.length()-1);
					}
				}
				
				list = "<div><a href='http://localhost:8080/TP_RESTful/rest/list/dir" +temp.substring(0,temp.lastIndexOf('/')+1) + "'>Dossier Parent</a></div><br>";
				
				list += "<table>" + 
							"<thead><tr>" + 
								"<th>Nom</th>" +
								"<th>Taille</th>" + 
								"<th>Date</th>" + 
							"</tr></thead>";
				for (FTPFile file : this.rest.list()) {
					list += "<tr>";
					
					if(!file.isDirectory()){
						list += "<td>" + file.getName() + "</td>";
					} else {
						if(currentPath.equals("/") && file.getName().equals("..")){
							list += "<td><a href='http://localhost:8080/TP_RESTful/rest/list/dir/'>" + file.getName() + "</a></td>";
						} else {
							list += "<td><a href='http://localhost:8080/TP_RESTful/rest/list/dir" + currentPath.replaceAll("(/)+", "/") + file.getName() + "/'>" + file.getName() + "</a></td>";
						}
					}
					list += "<td>" + file.getSize() + "</td>";
					list += "<td>" + file.getTimestamp().get(Calendar.DAY_OF_MONTH) + " " + file.getTimestamp().get(Calendar.MONTH) + " " + file.getTimestamp().get(Calendar.YEAR) +"</td>";
					list += "</tr>";
				}
				
				list += "</table>";
				
			} else {
				message = "Désolé vous n'avez pas accès à cette page";
			}
		} catch (SocketException e) {
			message = "Problème avec le socket !";
		} catch (IOException e) {
			e.printStackTrace();
			message = "La connexion n'a pas pu être faite";
		}

		test += message + "<br>" + list + "</body></html>";

		return test;
	}
	
}
